package com.ecut.property_project.config.security;

import com.ecut.property_project.model.character.Account;
import com.ecut.property_project.model.character.Role;
import com.ecut.property_project.service.impl.AccountServiceImpl;
import com.ecut.property_project.utils.JWTUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    AccountServiceImpl accountService;


    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，
     * 例如checkRole,checkPermission,@RequiresRoles("admin"),@RequiresPermissions("update")之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权~~~~~");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 1、取出account
        Account currentAccount = (Account) principalCollection.getPrimaryPrincipal(); //拿到Account对象
        Set<String> roles = new HashSet<>();
        // 2、数据库查询并设置用户权限;
        List<Role> roleList = accountService.getAccountRolesById(currentAccount.getId());
        for (Role role : roleList){
            roles.add(role.getName());
        }
        info.setRoles(roles);
        // 4、返回用户权限
        return info;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可，在需要用户认证和鉴权的时候才会调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        System.out.println("认证~~~~~~~");
        String token = (String) auth.getPrincipal();
        // 解密获得username，用于和数据库进行对比
        String tel = JWTUtils.getUsername(token);
        if (tel == null) {
            throw new AuthenticationException(" token错误，请重新登入！");
        }
        Account account = accountService.getAccount(tel);
        if (account == null) {
            throw new AccountException("账号不存在!");
        }
        if(JWTUtils.isExpire(token)){
            throw new AuthenticationException(" token过期，请重新登入！");
        }
        if (! JWTUtils.verify(token, tel, account.getPassword())) {
            throw new CredentialsException("密码错误!");
        }
        return new SimpleAuthenticationInfo(account, token, getName());
    }



}
